package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import server.catalina.*;
import server.request.Request;
import server.response.RequestProcessor;
import server.response.Response;
import server.servlet.HttpServlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 自定义启动类
 */
public class MyBootstrap {

    private Service service = new Service();

    /**
     * servlet集合
     */
    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();


    // 定义一个线程池
    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    private static int maximumPoolSize = corePoolSize * 2;
    private static long keepAliveTime = 100L;
    private static TimeUnit unit = TimeUnit.SECONDS;
    private static BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
    private static ThreadFactory threadFactory = Executors.defaultThreadFactory();
    private static RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            unit,
            workQueue,
            threadFactory,
            handler
    );

    public void start() throws Exception {
        //1.加载server.xml
        loadServer();
        //2.获取端口号
        int port = Integer.parseInt(service.getConnector().getPort());
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        //返回html静态资源文件
/*        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.doOutputHtml(request.getUrl(), service);
            socket.close();
        }*/

        //可以请求动态资源（Servlet）
/*        while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if (servletMap.get(request.getUrl()) == null) {
                response.doOutputHtml(request.getUrl(), service);
            } else {
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        }*/

        /*多线程改造（使用线程池）*/
        while (true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            requestProcessor.setService(service);
            threadPoolExecutor.execute(requestProcessor);
        }

    }

    /**
     * 加载server.xml
     */
    private void loadServer() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            //1.获取Connector的端口号
            Element connectorNode = (Element) rootElement.selectSingleNode("//Connector");
            String port = connectorNode.attributeValue("port");
            Connector connector = new Connector();
            connector.setPort(port);
            //2.获取Engine
            Element engineElement = (Element) rootElement.selectSingleNode("//Engine");
            //3.获取Engine的host
            List<Element> hostElementList = engineElement.selectNodes("//Host");
            //4.遍历host
            List<Host> hostList = new ArrayList<>();
            if (hostElementList != null && hostElementList.size() > 0) {
                for (Element hostElement : hostElementList) {
                    Host host = new Host();
                    host.setName(hostElement.attributeValue("name"));
                    host.setAppBase(hostElement.attributeValue("appBase"));
                    //获取host节点下的Context
                    List<Element> contextElementList = hostElement.selectNodes("//Context");
                    List<Context> contextList = new ArrayList<>();
                    if (hostElementList.size() > 0) {
                        for (Element contextElement : contextElementList) {
                            String docBase = contextElement.attributeValue("docBase");
                            String path = contextElement.attributeValue("path");
                            Context context = new Context(docBase, path);
                            contextList.add(context);
                            //加载动态资源servlet,如果context配置有web.xml,则认为有
                            loadWebXml(docBase, path);
                        }
                    }
                    host.setContexts(contextList);
                    hostList.add(host);
                }
            }
            Engine engine = new Engine();
            engine.setHosts(hostList);
            //封装service对象
            service.setConnector(connector);
            service.setEngine(engine);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void loadWebXml(String docBase, String path) {
        if (docBase != null && docBase.contains("web.xml")) {
            loadServlet(docBase, path);
        }
    }

    private void loadServlet(String docBase, String path) {

        try {
            File file = new File(docBase);
            if (file.exists() && file.isDirectory()) {
                return;
            }
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(file);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.servlet.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(path + urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        MyBootstrap bootstrap = new MyBootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
